# -*- coding: utf-8 -*-
# @Time    : 2024/4/21 12:09
# @Author  : Alvin
# @File    : LogisticsBaseHandler.py
# @Des     : 处理物流的基类
import json
import os
import random

import requests
from geopy.distance import geodesic

from model.GetNumParam import GetNumParam
from server.handler.DatabaseHandler import DatabaseHandler
from concurrent.futures import ThreadPoolExecutor
import logging
import traceback
from utils import CheUtil, BussinessUtil
from constants import Constants


class LogisticsBaseHandler(object):

    def __init__(self):
        self.db_handler = DatabaseHandler()
        current_path = os.path.dirname(__file__)
        project_root = os.path.abspath(os.path.join(current_path, '../../..'))
        self.defaultFile = f"{project_root}/token.json"
        if os.path.exists(self.defaultFile):
            with open(self.defaultFile, mode='r', encoding='utf-8') as file:
                content = file.read()
                content_dict = json.loads(content)
                self.token = content_dict.get("token")
                self.requestToken = content_dict.get("requestToken")
        else:
            isSuccess = self.do_lan_qiao_login()
            if not isSuccess:
                raise Exception("创建单号前置步骤异常，请联系管理员")
            print("登录", isSuccess)

    def check_user_is_logined(self):
        """
        判断用户是否已经登录，如果掉线则调用登录接口，如果没有掉线则继续实现业务
        :return:
        """
        try:
            headers = CheUtil.get_request_header(self.token, self.requestToken)
            url = "https://apit9.lqfast.com/lanqiao-tms-app/web/common/getSkinData"
            u = CheUtil.get_param_u(self.token)
            data = {
                "m": "func",
                "n": "getSkinData",
                "p": {},
                "l": "",
                "v": "",
                "u": u,
                "r": "k",
                "s": "k",
                "t": BussinessUtil.get_current_timetamp()
            }
            resp_json = requests.post(url, headers=headers, json=data).json()
            logging.info(f"检查登录状态响应：{resp_json}")
            is_online = resp_json.get("success")
            if not is_online:
                isLoginSuccess = self.do_lan_qiao_login()
                if not isLoginSuccess:
                    return False
            return True
        except Exception as ex:
            logging.error(f"检查系统登录方法出现异常，异常内容：{str(ex)}")
            logging.error("检查系统登录方法出现异常:%s", traceback.format_exc())

    def do_lan_qiao_login(self):
        """
        车氏物流账号密码登录，此处登录使用的是固定账号密码
        :return:
        """
        try:
            headers = {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-cache",
                "content-type": "application/json; charset=UTF-8",
                "hango-origin": "lanqiao",
                "origin": "https://www.561861.cn",
                "pragma": "no-cache",
                "priority": "u=1, i",
                "referer": "https://www.561861.cn/",
                "sec-ch-ua": "\"Chromium\";v=\"136\", \"Google Chrome\";v=\"136\", \"Not.A/Brand\";v=\"99\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "cross-site",
                "tenantcode": "78210",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
            }
            url = "https://apit9.lqfast.com/lanqiao-tms-app/web/account/loginVerify"
            user_name = Constants.user_name
            pwd = BussinessUtil.get_encrypt_pwd(Constants.password)
            data = {
                "m": "func",
                "n": "loginVerify",
                "p": {
                    "webtoken": pwd,
                    "tmscode": "78210",
                    "loginname": user_name,
                    "pwd": pwd,
                    "officialwebsite": 1,
                    "verifycode": "",
                    "userid": "优斯雅通达",
                    "Password": pwd,
                    "storeProcedure": "QSP_GET_BASEINFO"
                },
                "l": "",
                "v": "",
                "u": {
                    "tmsCode": "78210",
                    "userId": user_name,
                    "tmsbshxsite": "",
                    "browserId": None
                },
                "r": "k",
                "s": "k",
                "t": BussinessUtil.get_current_timetamp()
            }
            resp_json = requests.post(url, headers=headers, json=data).json()
            is_logistics_success = resp_json.get("success")
            if is_logistics_success:
                login_data = resp_json.get("data")
                login_key = login_data.get("key")
                return self.get_user_info(login_key)
            return False
        except Exception as ex:
            logging.error(f"do_lan_qiao_login 异常：{str(ex)}")
            logging.error("do_lan_qiao_login 异常:%s", traceback.format_exc())
            return False

    def get_user_info(self, logistics_key):
        try:
            headers = {
                "accept": "*/*",
                "accept-language": "zh-CN,zh;q=0.9",
                "cache-control": "no-cache",
                "content-type": "application/json; charset=UTF-8",
                "hango-origin": "lanqiao",
                "origin": "https://t9bs.lqfast.com",
                "pragma": "no-cache",
                "priority": "u=1, i",
                "referer": "https://t9bs.lqfast.com/",
                "requesttoken": "0A70ABB1C58F4DE290D67BEFAB9A92F6",
                "sec-ch-ua": "\"Chromium\";v=\"136\", \"Google Chrome\";v=\"136\", \"Not.A/Brand\";v=\"99\"",
                "sec-ch-ua-mobile": "?0",
                "sec-ch-ua-platform": "\"Windows\"",
                "sec-fetch-dest": "empty",
                "sec-fetch-mode": "cors",
                "sec-fetch-site": "same-site",
                "tenantcode": "78210",
                "token;": "",
                "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/136.0.0.0 Safari/537.36"
            }
            url = "https://apit9.lqfast.com/lanqiao-tms-app/web/account/loginGetUserInfo"
            data = {
                "m": "func",
                "n": "loginGetUserInfo",
                "p": {
                    "key": logistics_key
                },
                "l": "",
                "v": "",
                "u": {},
                "r": "k",
                "s": "k",
                "t": BussinessUtil.get_current_timetamp()
            }
            resp_json = requests.post(url, headers=headers, json=data).json()
            status = resp_json.get("success")
            if not status:
                return False
            user_info = resp_json.get("data")
            self.token = user_info.get("token")
            self.requestToken = user_info.get("requestToken")

            write_data = {
                "token": user_info.get("token"),
                "requestToken": user_info.get("requestToken"),
            }
            with open(self.defaultFile, mode='w', encoding='utf-8') as file:
                file.write(json.dumps(write_data))
            return True
        except Exception as ex:
            logging.error(f"get_user_info 异常：{str(ex)}")
            logging.error("get_user_info 异常:%s", traceback.format_exc())
            return False
